<template>
    <div>
        <slot name="setting"></slot>
        <van-form>
            <blank-place-holder  v-if="item.data.components.length === 0" msg="选择此处拖拽表单控件到此处"></blank-place-holder>
            <draggable
                    tag="div"
                    :style="{
                        height: item.data.components.length === 0 ? '204px' : 'auto'
                    }"
                    :list="item.data.components"
                    group="form-components"
                    v-bind="dragOptions"
                    @start="drag = true"
                    @end="drag = false"
                    @change="onDragEnd"
            >
                <component
                        v-for="(component, index) in item.data.components"
                        :key="index"
                        :submit="function (){
                            return clickedFormItem(component)
                        }"
                        :selected="function (){
                            return clickedFormItem(component)
                        }"
                        :is="component.preview.type"
                        v-bind:data="component.data"
                >
                </component>
            </draggable>
        </van-form>
    </div>
</template>

<script>
    import Draggable from 'vuedraggable'
    import BlankPlaceHolder from "../../BlankPlaceHolder";
    export default {
        components: {
            Draggable,
            BlankPlaceHolder
        },
        props: {
            item: Object
        },
        data() {
            return {
                drag: false
            }
        },
        methods: {
            clickedFormItem(component) {
                this.$store.commit('setSelectedComponent', {
                    config: this.item.config,
                    data: this.item.data,
                });
                this.$store.commit('setSelectedSubComponent', component)
            },
            onDragEnd(event){
                if(event.added !== undefined){
                    let element = event.added.element
                    this.clickedFormItem(element)
                }
            }
        },
        computed: {
            dragOptions() {
                return {
                    animation: 200,
                    group: "form-drag-group",
                    disabled: false,
                    ghostClass: "ghost"
                };
            },
        }
    }
</script>